<template>
  <div class="updata-container">
    <div class="header">
      <el-button @click="goBack" class="back-button">返回</el-button>
    </div>
    <!-- 商品列表表格 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="title" label="商品名称" />
      <el-table-column prop="price" label="价格" width="120" />
      <el-table-column prop="content" label="描述" />
      <el-table-column prop="image" label="图片" width="120">
        <template #default="scope">
          <el-image
            style="width: 100%; height: 100%"
            :src="scope.row.image"
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 修改对话框 -->
    <el-dialog v-model="dialogVisible" title="修改商品信息" width="50%">
      <el-form :model="form" label-width="120px">
        <el-form-item label="商品名称">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model="form.price" type="number" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="form.content" type="textarea" />
        </el-form-item>
        <el-form-item label="图片链接">
          <el-input v-model="form.image" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdate">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { ArrowLeft } from '@element-plus/icons-vue'
import axios from 'axios'

const router = useRouter()

// 返回上一页
const goBack = () => {
  router.back()
}

// 表格数据
const tableData = ref([])

// 获取商品列表
const fetchList = async () => {
  try {
    const response = await axios.post('http://localhost:3005/cart/list')
    console.log('后端返回数据:', response.data) // 添加日志输出
    if (response.data.success) {
      if (Array.isArray(response.data.result)) {
        // 添加图片URL的服务器地址前缀
        tableData.value = response.data.result.map(item => ({
          ...item,
          image: item.image.startsWith('http') ? item.image : `http://localhost:3005${item.image}`
        }))
      } else {
        console.error('返回的数据格式不正确:', response.data)
        ElMessage.error('数据格式不正确')
      }
    } else {
      console.error('获取商品列表失败:', response.data.message)
      ElMessage.error(response.data.message || '获取商品列表失败')
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败，请稍后重试')
  }
}

// 在组件挂载时获取商品列表
onMounted(() => {
  fetchList()
})

// 对话框显示状态
const dialogVisible = ref(false)

// 表单数据
const form = ref({
  id: '',
  title: '',
  price: '',
  content: '',
  image: ''
})

// 处理修改按钮点击
const handleEdit = (row) => {
  form.value = { ...row }
  dialogVisible.value = true
}

// 处理更新操作
const handleUpdate = async () => {
  try {
    // 数据验证
    if (!form.value.title.trim()) {
      ElMessage.error('商品名称不能为空')
      return
    }
    if (isNaN(Number(form.value.price)) || Number(form.value.price) < 0) {
      ElMessage.error('请输入有效的价格')
      return
    }

    // 处理图片路径，确保只保存相对路径
    let imagePath = form.value.image
    if (imagePath.startsWith('http://localhost:3005')) {
      imagePath = imagePath.replace('http://localhost:3005', '')
    }

    // 确保price是数字类型
    const formData = {
      ...form.value,
      price: Number(form.value.price),
      image: imagePath
    }

    const response = await axios.post('http://localhost:3005/cart/update', formData)
    if (response.data.success) {
      const index = tableData.value.findIndex(item => item.id === formData.id)
      if (index !== -1) {
        tableData.value[index] = { 
          ...formData,
          image: formData.image.startsWith('http') ? formData.image : `http://localhost:3005${formData.image}`
        }
        ElMessage.success('修改成功')
        dialogVisible.value = false
        // 刷新列表
        await fetchList()
      }
    } else {
      ElMessage.error(response.data.message || '修改失败：' + (response.data.error || '未知错误'))
    }
  } catch (error) {
    console.error('更新商品失败:', error)
    const errorMessage = error.response?.data?.message || error.message || '服务器连接失败'
    ElMessage.error(`更新商品失败：${errorMessage}`)
  }
}

</script>

<style scoped>
.updata-container {
  padding: 20px;
  margin-left: -220px;
  width: 830px;
  position: relative;
}

.header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.back-button {
  margin-right: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>